import {
	computed,
	reactive,
	ref
} from "vue";

import store from "../../../store";
export default function useCompliments(data) {
	//用户数据
	const userInfo = computed(() => {
		return store.state.userInfo
	});
	//获取文章信息
	const {
		articleData,
		$http
	} = data;
	//是否对文章进行点赞
	const isCompliments = computed(() => {
		try {
			return (
				userInfo.value && userInfo.value.thumbs_up_article_ids.includes(articleData.value._id)
			);
		} catch (e) {
			return false;
		}
	});
	const updateCompliments = async () => {
		const {
			returnMsg
		} = await $http.update_complimets({
			articleId: articleData.value._id,
			userId: userInfo.value._id,
		});
		return returnMsg;
	};
	const updateLoacalCompliments = async () => {
		let thumbs = [...userInfo.value.thumbs_up_article_ids];
		if (thumbs.includes(articleData.value._id)) {
			//删除
			thumbs = thumbs.filter((item) => item !== articleData.value._id);
			articleData.value.thumbs_up_count -= 1;
		} else {
			//增加
			thumbs.push(articleData.value._id);
			articleData.value.thumbs_up_count += 1;
		}
		//更新store和localstorage
		store.commit("updateUserInfo", {
			...userInfo.value,
			thumbs_up_article_ids: thumbs,
		});
	};
	return {
		isCompliments,
		updateCompliments,
		updateLoacalCompliments
	};
}